package com.shuma.shopmanage.security;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.shuma.shopmanage.common.model.LoginUser;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SecurityContextHolder
{
    private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();

    private static final String LOGIN_USER = "loginUser";


    public static void set(String key, Object value)
    {
        Map<String, Object> map = getLocalMap();
        map.put(key, value == null ? StringUtils.EMPTY : value);
    }

    public static String get(String key)
    {
        Map<String, Object> map = getLocalMap();
        return (String) map.getOrDefault(key, StringUtils.EMPTY);
    }

    public static <T> T get(String key, Class<T> clazz)
    {
        Map<String, Object> map = getLocalMap();
        return (T) (map.getOrDefault(key, null));
    }

    public static Map<String, Object> getLocalMap()
    {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null)
        {
            map = new ConcurrentHashMap<String, Object>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

    public static void setLocalMap(Map<String, Object> threadLocalMap)
    {
        THREAD_LOCAL.set(threadLocalMap);
    }

    public static void setLoginUser(LoginUser loginUser) {
        set(LOGIN_USER, loginUser);
    }

    public static LoginUser getLoginUser() {
        return get(LOGIN_USER, LoginUser.class);
    }

    public static void remove()
    {
        THREAD_LOCAL.remove();
    }


}